/**
 * Code Sample for
 * Runtime Performance & Availability Monitoring for Java Systems.
 * IBM DevelperWorks.
 * Nicholas Whitehead (whitehead.nicholas@gmail.com)
 */

package org.digitarts.rtms.spring.collectors.management;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;

import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

import org.digitarts.rtms.spring.collectors.CollectorBase;
import org.springframework.jmx.export.naming.ObjectNamingStrategy;

public class DelegatingNamingStrategy implements ObjectNamingStrategy
{

	private Map<Class<?>, Method>	methodCache	= Collections.synchronizedMap(new WeakHashMap<Class<?>, Method>());

	/**
	 * @param object
	 * @param name
	 * @return ObjectName
	 * @throws MalformedObjectNameException
	 */
	public ObjectName getObjectName(Object object, String name) throws MalformedObjectNameException
	{
		if (object instanceof CollectorBase)
		{
			Class<?> clazz = object.getClass();
			Method method = methodCache.get(clazz);
			try
			{
				if (null == method)
				{
					method = clazz.getMethod("getObjectName", new Class[] {});
					methodCache.put(clazz, method);
				}
				return (ObjectName) method.invoke(object, new Object[] {});
			}
			catch (Exception e)
			{
				throw new RuntimeException("Failed to acquire ObjectName", e);
			}
		}
		else
		{
			throw new RuntimeException("Not an instance of CollectorBase");
		}
	}

}
